package com.jinlejia.erp.ui.common;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jinlejia.erp.BuildConfig;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityLoginBinding;
import com.utils.MD5Utils;
import com.utils.updateapp.UpdateUtils;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.MediaType;


/**
 * 登录（activity）
 */

public class LoginActivity extends AppCompatActivity {
    private ActivityLoginBinding binding;
    private String registrationID;

    ProgressDialog progressDialog;

    //动态授权
    final int REQUEST_EXTERNAL_STORAGE = 1;
    String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        binding.setEvent(this);
        JPushInterface.requestPermission(this);
        initView();
        initEvent();
    }



    /**
     * 检查更新方法
     */
    public void checkupdate(){
        //检查授权
        int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions( this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }else {
            UpdateUtils.getInstance(this).checkAndUpdate(BuildConfig.VERSION_NAME);
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        progressDialog = new ProgressDialog(this, "请稍后...",false);
        registrationID = JPushInterface.getRegistrationID(this);
        binding.versionCode.setText(String.format("©  %s", BuildConfig.VERSION_NAME));
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        binding.userNameEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    binding.userNameLine.setBackgroundResource(R.color.yellow);
                    binding.userNameEdit.setTextColor(getResources().getColor(R.color.yellow));
                }else {
                    binding.userNameLine.setBackgroundResource(R.color.hintColor);
                    binding.userNameEdit.setTextColor(getResources().getColor(R.color.hintColor));
                }
            }
        });
        binding.userPasswordEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    binding.userPasswordLine.setBackgroundResource(R.color.yellow);
                    binding.userPasswordEdit.setTextColor(getResources().getColor(R.color.yellow));
                }else {
                    binding.userPasswordLine.setBackgroundResource(R.color.hintColor);
                    binding.userPasswordEdit.setTextColor(getResources().getColor(R.color.hintColor));
                }
            }
        });

    }

    public void onClick(View view) {
        if (TextUtils.isEmpty(binding.userNameEdit.getText().toString())){
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
        }else if (TextUtils.isEmpty(binding.userPasswordEdit.getText().toString())){
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
        }else if( TextUtils.isEmpty( registrationID ) ) {
            registrationID = JPushInterface.getRegistrationID(this);
            Toast.makeText(this, "设备码获取失败，请重试!", Toast.LENGTH_SHORT).show();
        }else{
            Login();
        }
    }

    /**
     * 登录
     */
    private void Login() {
        progressDialog.show();

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pin", binding.userNameEdit.getText().toString());
            jsonObject.put("password", MD5Utils.md5(binding.userPasswordEdit.getText().toString()));
            jsonObject.put("deviceCode", registrationID);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils
                .postString()
                .url(ApiConfig.LOGIN)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                            Toast.makeText(LoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (Integer.parseInt(response.get("code").toString())==200) {
                            Intent intent = new Intent(LoginActivity.this,VerificationActivity.class);
                            intent.putExtra("tel",response.get("data").toString());
                            intent.putExtra("pin",binding.userNameEdit.getText().toString());
                            intent.putExtra("password",binding.userPasswordEdit.getText().toString());
                            intent.putExtra("deviceCode",registrationID);
                            startActivity(intent);
                        }else if (Integer.parseInt(response.get("code").toString())==122){
                            //跳转申请登录页面
                            Intent intent = new Intent(LoginActivity.this,LoginApplyActivity.class);
                            intent.putExtra("pin",binding.userNameEdit.getText().toString());
                            intent.putExtra("password",binding.userPasswordEdit.getText().toString());
                            intent.putExtra("deviceCode",registrationID);
                            startActivity(intent);
                        }else{
                            CustomToast.showToast(LoginActivity.this,String.valueOf(response.get("message")),1500);
                        }

                    }
                });
    }
    PermissionDialog permissionDialog;
    @Override
    protected void onResume() {
        super.onResume();
        if (permissionDialog==null){
            permissionDialog = new PermissionDialog(this);
        }
        //检查权限
        XXPermissions.with(this)
                .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll && permissionDialog.isShowing()) {
                            permissionDialog.dismiss();
                        }
                        checkupdate();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (null != permissionDialog && !permissionDialog.isShowing())
                            permissionDialog.show();
                        permissionDialog.setConfirmListener(new PermissionDialog.OnConfirmListener() {
                            @Override
                            public void confirm() {
                                XXPermissions.gotoPermissionSettings(LoginActivity.this);
                            }
                        });
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
